package com.duban.test.plugins;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
* @Description: 操作文件公共类
* @Company:TGRF
* @author:lijianjun
* 
* @date: 2013-10-14 下午02:24:17
* @version V1.0
*/
public class FileUtil {
	
	private static final int BUFFER_SIZE = 16 * 1024;
	public static final String FILEPATH = "/front/upload/file/";
	
	/**
	 * 把数据写至文件中
	 * @param filePath
	 * @param data
	 */
	public static void writeFile(String filePath,String data){
		FileOutputStream fos = null;
		OutputStreamWriter writer=null;
		try {
			fos = new FileOutputStream(new File(filePath));
			writer=new OutputStreamWriter(fos, "UTF-8");			
			writer.write(data);
		} catch (Exception ex) {
		} finally {
			try {
				if(writer!=null){
					writer.close();
				}
				if (fos != null){
					fos.close();
				}
			} catch (Exception e) {
			}
		}		
	}
	
	/**
	 * 读取文件内容
	 * @param filePath
	 * @return
	 */
	public static String readFile(String filePath){
		 StringBuffer buffer = new StringBuffer();
		// 读出这个文件的内容
		try{
			File file = new File(filePath);
		    FileInputStream fis = null;
		    BufferedReader breader=null;
		    try {
		      fis = new FileInputStream(file);
		      InputStreamReader isReader=new InputStreamReader(fis,"UTF-8");
		      breader=new BufferedReader(isReader);
		      String line;
		      while((line=breader.readLine())!=null) {
		        buffer.append(line);
		        buffer.append("\r\n");
		      }
		      breader.close();
		      isReader.close();
		      fis.close();
		      
		    } catch (FileNotFoundException e) {
		    } catch (IOException e) {
		    }
		}catch(Exception e){
		}
		return buffer.toString();
	}
	
	/**
	 * 复制文件
	 * 
	 * @param src
	 * @param dst
	 */
	public static void copyFile(File src, File dst) {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(dst),
					BUFFER_SIZE);
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 获取文件名的前缀
	 * @param fileName
	 * @return
	 */
	public static String getFilePrefix(String fileName){
		int splitIndex = fileName.lastIndexOf(".");
		if(splitIndex==-1)
			return "";
		else
			return fileName.substring(0, splitIndex);
	}
	
	/**
	 * 获取文件名的后缀
	 * @param fileName
	 * @return
	 */
	public static String getFileSufix(String fileName){
		int splitIndex = fileName.lastIndexOf(".");
		if(splitIndex==-1)
			return "";
		else
			return fileName.substring(splitIndex + 1);
	}
	
	/*
	 * 删除文件
	 */
	 public static void  deleteFile(String fileName) {
		   File  file = new File(fileName);
		   if(file.exists()) {
			   file.delete();
		   }
	   }
	 
	 //创建文件目录
	public static boolean mkDir(String dir) {
		File file = new File(dir);
		if (!file.exists()) {
			return file.mkdirs();
		}
		return true;
	}
	
	
	//zip
	public static void zipFile(String filename,String tempFilePath) throws Exception{
		FileOutputStream fos = null;
        ZipOutputStream zipOut = null;
        FileInputStream fis = null;
        File zipFileTemp = new File( filename);
        String [] files = ( new File( tempFilePath ) ).list();
        fos = new FileOutputStream( zipFileTemp );
        zipOut = new ZipOutputStream( fos );
        int i = 0;
    	for ( i = 0; i < files.length; i++ ) {
    		File f = new File( files[i] );
            fis = new FileInputStream( tempFilePath + "/" + files[i] );
            ZipEntry ze = new ZipEntry( f.getName() );
            zipOut.putNextEntry( ze );
            int c = 0;
            while ( ( c = fis.read() ) != -1 ) {
            	zipOut.write( c );
            }
            fis.close();
    	}
        zipOut.close();
        fis.close();
        fos.close();
	}
	
	//delete this dir and all files of the dir 
	public static void delAllFile(String filePath) {
		File file = new File(filePath);
		File[] fileList = file.listFiles();
		String dirPath = null;
		if (fileList != null) {
			for (int i = 0; i < fileList.length; i++) {
				if (fileList[i].isFile()) {
					fileList[i].delete();
				}
				if (fileList[i].isDirectory()) {
					dirPath = fileList[i].getPath();
					delAllFile(dirPath);
				}
			}
			file.delete();
		}
	}
	/**
	 * 删除目录下的子文件
	 * @author wangzhe/bdjb0064
	 * date: 2015-1-5 上午11:03:55 <br/>
	 * @param filePath
	 */
	public static void delAllSubFile(String filePath) {
		File file = new File(filePath);
		File[] fileList = file.listFiles();
		String dirPath = null;
		if (fileList != null) {
			for (int i = 0; i < fileList.length; i++) {
				if (fileList[i].isFile()) {
					fileList[i].delete();
				}
				if (fileList[i].isDirectory()) {
					dirPath = fileList[i].getPath();
					delAllFile(dirPath);
				}
			}
		}
	}
	
	/**
	 * 
	 * @method: getBySysFilePath
	 * @Description: 根据系统读取服务器路径
	 *
	 * @return 返回到项目名称
	 *
	 * @author: lijianjun
	 * @date 2014-7-4 下午2:55:24
	 * @return String
	 */
	public static String getBySysFilePath(String pa){
		String sysName = System.getProperty("os.name").toLowerCase();
		if(sysName.indexOf("window")>=0){
			pa = pa.substring(1,pa.lastIndexOf("WEB-INF/classes"));
		}else{
			pa = pa.substring(0,pa.lastIndexOf("WEB-INF/classes"));
		}
		return pa;
	}
	
	/**
	 * 
	* @method: getTempFileList
	* @Description: 读取一个文件夹下的所有文件
	*
	* @param path 文件夹路径
	* @return
	* @return List<File>
	*
	* @author: lijianjun
	* @date 2014-7-7 下午6:09:25
	 */
	public static List<File> getTempFileList(String path){
		File root = new File(path);
		List<File> fileList = new ArrayList<File>();
		if(root.isDirectory()){
			String[] fileStr = root.list();
			for (int i = 0; i < fileStr.length; i++) {
				File readfile = new File(path + "/" + fileStr[i]);
				if (!readfile.isDirectory()) {
					fileList.add(readfile);
				}
			}
		}
		return fileList;
	}
	
	/**
	 * 
	 * @method: uploadFile
	 * @Description: 上传一个文件
	 *
	 * @param file 需要上传的文件
	 * @param path 上传文件的地址
	 * @return void
	 *
	 * @author: lijianjun
	 * @date 2014-7-8 下午1:41:03
	 */
	public static void uploadFile(File file,String path){
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(path),
					BUFFER_SIZE);
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 新建文件
	 * @author wangzhe/bdjb0064
	 * @param fullFile 文件路径+文件名
	 * @return
	 */
	public static Boolean createNewFile(String fullFile){
		File file = new File(fullFile);
		if (!file.exists()) {
			try {
				return file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return true;
	}

}
